import React from 'react';
import {
    Modal,
    Form,
    Input,
    Select,
    InputNumber,
    Row,
    Col,
    Transfer,
    Divider,
    Checkbox,
    TimePicker,
    Button,
    Space
} from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import moment from 'moment';

const { Option } = Select;
const { TextArea } = Input;

const PackageForm = ({
    visible,
    formTitle,
    onCancel,
    formKey,
    packageForm,
    handleFormSubmit,
    currentPackage,
    loading,
    selectedStores,
    storeTargetKeys,
    handleStoreChange,
    selectedVenues,
    venueTargetKeys,
    handleVenueChange,
}) => {
    return (
        <Modal
            title={formTitle}
            visible={visible}
            onCancel={onCancel}
            footer={null}
            width={800}
            destroyOnClose
        >
            <Form
                key={formKey} // 关键：强制Form刷新，解决Form.List回显异常
                form={packageForm}
                name="packageForm"
                onFinish={handleFormSubmit}
                autoComplete="off"
                layout="vertical"
                preserve={false}
                initialValues={currentPackage}
            >
                <Row gutter={24}>
                    <Col span={12}>
                        <Form.Item
                            label="套餐名称"
                            name="name"
                            rules={[{ required: true, message: '请输入套餐名称' }]}
                        >
                            <Input placeholder="请输入套餐名称" />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            label="套餐价格"
                            name="price"
                            rules={[{ required: true, message: '请输入套餐价格' }]}
                        >
                            <InputNumber
                                placeholder="请输入套餐价格"
                                min={0}
                                precision={2}
                                style={{ width: '100%' }}
                            />
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={24}>
                    <Col span={12}>
                        <Form.Item
                            label="使用时长(小时)"
                            name="duration"
                            rules={[{ required: true, message: '请输入使用时长' }]}
                        >
                            <InputNumber
                                placeholder="请输入使用时长"
                                min={1}
                                style={{ width: '100%' }}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            label="排序"
                            name="sort_order"
                            rules={[{ required: true, message: '请输入排序' }]}
                        >
                            <InputNumber
                                placeholder="请输入排序"
                                min={0}
                                style={{ width: '100%' }}
                            />
                        </Form.Item>
                    </Col>
                </Row>
                <Form.Item
                    label="套餐描述"
                    name="description"
                >
                    <TextArea rows={4} placeholder="请输入套餐描述" />
                </Form.Item>
                <Form.Item
                    label="状态"
                    name="status"
                    rules={[{ required: true, message: '请选择状态' }]}
                >
                    <Select placeholder="请选择状态">
                        <Option value={1}>启用</Option>
                        <Option value={0}>禁用</Option>
                    </Select>
                </Form.Item>
                
                <Divider orientation="left">适用门店</Divider>
                <Form.Item>
                    <Transfer
                        dataSource={selectedStores}
                        titles={['可选门店', '已选门店']}
                        targetKeys={storeTargetKeys}
                        onChange={handleStoreChange}
                        render={item => item.title}
                        listStyle={{
                            width: 300,
                            height: 300,
                        }}
                    />
                </Form.Item>
                
                <Divider orientation="left">适用场地</Divider>
                <Form.Item>
                    <Transfer
                        dataSource={selectedVenues}
                        titles={['可选场地', '已选场地']}
                        targetKeys={venueTargetKeys}
                        onChange={handleVenueChange}
                        render={item => `${item.title} (${item.description})`}
                        listStyle={{
                            width: 300,
                            height: 300,
                        }}
                    />
                </Form.Item>
                
                <Divider orientation="left">可用时间设置</Divider>

                <Form.Item
                    label="可用星期"
                    name="available_weekdays"
                    rules={[{ required: true, message: '请选择可用星期' }]}
                >
                    <Checkbox.Group
                        options={[
                            { label: '周一', value: 1 },
                            { label: '周二', value: 2 },
                            { label: '周三', value: 3 },
                            { label: '周四', value: 4 },
                            { label: '周五', value: 5 },
                            { label: '周六', value: 6 },
                            { label: '周日', value: 7 },
                        ]}
                    />
                </Form.Item>

                <Form.Item label="可用时间段">
                    <Form.List name="available_times">
                        {(fields, { add, remove }) => {
                            // 防御性处理，确保fields为数组，避免非数组导致的展开报错。
                            const safeFields = Array.isArray(fields) ? fields : [];
                            return (
                                <>
                                    {safeFields.map(({ key, name, ...restField }) => (
                                        <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                                            <Form.Item
                                                {...restField}
                                                name={[name, 'timeRange']}
                                                rules={[{ required: true, message: '请选择时间范围' }]}
                                            >
                                                <TimePicker.RangePicker format="HH:mm" />
                                            </Form.Item>
                                            <MinusCircleOutlined onClick={() => remove(name)} />
                                        </Space>
                                    ))}
                                    <Form.Item>
                                        <Button 
                                            type="dashed" 
                                            onClick={() => {
                                                // 安全地添加新时间段，确保传入正确的默认值
                                                add({ timeRange: [moment('00:00', 'HH:mm'), moment('23:59', 'HH:mm')] });
                                            }} 
                                            block 
                                            icon={<PlusOutlined />}
                                        >
                                            添加时间段
                                        </Button>
                                    </Form.Item>
                                </> 
                            );
                        }}
                    </Form.List>
                </Form.Item>
                
                <Form.Item>
                    <Space>
                        <Button type="primary" htmlType="submit" loading={loading}>
                            提交
                        </Button>
                        <Button onClick={onCancel}>取消</Button>
                    </Space>
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default PackageForm;